package io.renren.modules.sys.controller;

import io.renren.common.annotation.SysLog;
import io.renren.common.utils.*;
import io.renren.common.validator.Assert;
import io.renren.common.validator.ValidatorUtils;
import io.renren.common.validator.group.AddGroup;
import io.renren.common.validator.group.UpdateGroup;
import io.renren.modules.sys.entity.SysUserEntity;
import io.renren.modules.sys.service.SysUserRoleService;
import io.renren.modules.sys.service.SysUserService;
import org.apache.commons.lang.ArrayUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.apache.shiro.crypto.hash.Sha256Hash;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.text.ParseException;
import java.util.List;
import java.util.Map;

/**
 * 系统用户
 * 
 * @author chenshun
 * @email sunlightcs@gmail.comqueryAll
 * @date 2016年10月31日 上午10:40:10
 */
@RestController
@RequestMapping("/sys/user")
public class SysUserController extends AbstractController {
	@Autowired
	private SysUserService sysUserService;
	@Autowired
	private SysUserRoleService sysUserRoleService;
	
	/**
	 * 所有用户列表
	 */
	@RequestMapping("/list")
	@RequiresPermissions("sys:user:list")
	public R list(@RequestParam Map<String, Object> params){
		//查询列表数据
		Query query = new Query(params);
		List<SysUserEntity> userList = sysUserService.queryList(query);
		int total = sysUserService.queryTotal(query);
		
		PageUtils pageUtil = new PageUtils(userList, total, query.getLimit(), query.getPage());
		
		return R.ok().put("page", pageUtil);
	}

	/**
	 * 查询所有项目经理
	 */
	@RequestMapping("/listpm")
	@RequiresPermissions("sys:user:listpm")
	public R queryPm(){
		List<SysUserEntity> listpm = sysUserService.queryPm();

		return R.ok().put("pmList", listpm);
	}
	
	/**
	 * 获取登录的用户信息
	 * @throws ParseException 
	 */
	@RequestMapping("/info")
	public R info() throws ParseException{
		//用来判断该用户是否
		R r=new R();
		if(DateUtils.dayCompare(getUser().getCreateTime())==6) {
				r.put("msg", "长时间未修改密码，建议修改密码！");	
		}
		return r.put("user", getUser());
	}
	
	/**
	 * 修改登录用户密码
	 */
	@SysLog("修改密码")
	@RequestMapping("/password")
	public R password(String user){
		try{
			//解密user
			String aesUser = AesUtil.aesDecrypt(user.replaceAll(" ","+"));
			//获取第一个“=”的位置
			int index1 = aesUser.indexOf("=");
			//获取第二个“=”的位置
			int index2 = aesUser.indexOf("=", index1 + 1);
			//获取第一个“&”的位置
			int index4 = aesUser.indexOf("&");
			//截取用户名
			String password = aesUser.substring(index1+1, index4);
			System.out.println("****旧密码***"+password);
			//截取密码
			String newPassword = aesUser.substring(index2+1);
			System.out.println("****新密码***"+newPassword);
			//String password, String newPassword
			Assert.isBlank(newPassword, "新密码不为能空");

			//sha256加密
			password = new Sha256Hash(password, getUser().getSalt()).toHex();
			//sha256加密
			newPassword = new Sha256Hash(newPassword, getUser().getSalt()).toHex();

			//更新密码
			int count = sysUserService.updatePassword(getUserId(), password, newPassword);
			if(count == 0){
				return R.error("原密码不正确");
			}
			return R.ok();
		}catch (Exception e){
			return R.error("未知错误");
		}

	}
	
	/**
	 * 用户信息
	 * @throws ParseException 
	 */
	@RequestMapping("/info/{userId}")
//	@RequiresPermissions("sys:user:info")
	public R info(@PathVariable("userId") Long userId) throws ParseException{
		SysUserEntity user = sysUserService.queryObject(userId);
		
		//获取用户所属的角色列表
		List<Long> roleIdList = sysUserRoleService.queryRoleIdList(userId);
		user.setRoleIdList(roleIdList);
		return R.ok().put("user", user);
	}
	
	/**
	 * 保存用户
	 */
	@SysLog("保存用户")
	@RequestMapping("/save")
	@RequiresPermissions("sys:user:save")
	public R save(@RequestBody SysUserEntity user){
		ValidatorUtils.validateEntity(user, AddGroup.class);
		
		user.setCreateUserId(getUserId());
		sysUserService.save(user);
		
		return R.ok();
	}
	
	/**
	 * 修改用户
	 */
	@SysLog("修改用户")
	@RequestMapping("/update")
	@RequiresPermissions("sys:user:update")
	public R update(@RequestBody SysUserEntity user){
		ValidatorUtils.validateEntity(user, UpdateGroup.class);
		
		user.setCreateUserId(getUserId());
		SysUserEntity userEntity = sysUserService.queryByUserName(user.getUsername());
		if (userEntity == null){
			return R.error("用户不存在！");
		}
		user.setSalt(userEntity.getSalt());
		sysUserService.update(user);
		
		return R.ok();
	}
	
	/**
	 * 删除用户
	 */
	@SysLog("删除用户")
	@RequestMapping("/delete")
	@RequiresPermissions("sys:user:delete")
	public R delete(@RequestBody Long[] userIds){
		if(ArrayUtils.contains(userIds, 1L)){
			return R.error("系统管理员不能删除");
		}
		
		if(ArrayUtils.contains(userIds, getUserId())){
			return R.error("当前用户不能删除");
		}
		
		sysUserService.deleteBatch(userIds);
		
		return R.ok();
	}

	//设置任务责任人
	@RequestMapping("/getUpPerson")
	public R getUpPerson(){
        List<Map<String,Object>> mapList = sysUserService.getUpPerson();
		return R.ok().put("userList",mapList);
	}

	//查询所有用户
	@RequestMapping("/queryAll")
	public R queryAll(){
		List<SysUserEntity> userList = sysUserService.queryAll();
		return R.ok().put("userList",userList);
	}
}
